import connector.DatabaseDriver
from connector.DatabaseDriver import DatabaseDriver


def register_user(driver: DatabaseDriver, username: str, password: str, role: int):
    result: tuple = driver.select_one(
        'select user_id from user where user_name = "{}"'.format(username), log=True)
    if result is None:
        update: int = driver.insert(
            'insert into user(user_name, user_password, user_role) values ("{}","{}",'
            '{})'.format(username, password, role), log=True)
    else:
        return 0
    return update


def login(driver: DatabaseDriver, username: str, password: str) -> tuple:
    result: tuple = driver.select_one(
        'select user_id, user_role from account where username = "{}" and '
        'password = "{}"'.format(username, password), log=True)
    return result


def get_users(driver: DatabaseDriver) -> tuple:
    result: tuple = driver.select_all("select * from user")
    return result


def update_user(driver: DatabaseDriver, user_id: int, username: str, password: str, role: int):
    result: int = driver.update(
        'update user set username="{}", password="{}",user_role={} where '
        'user_id={}'.format(username, password, role, user_id))
    return result


def get_user_by_id(driver: DatabaseDriver, user_id: int) -> tuple:
    result: tuple = driver.select_one(sql="select * from account where user_id={}".format(user_id))
    return result


def get_user_by_username(driver: DatabaseDriver, user_name: str) -> bool:
    result: tuple = driver.select_one(sql='select * from account where user_name="{}"'.format(user_name))
    if len(result) == 1:
        return True
    return False


def get_username_by_user_id(driver: DatabaseDriver, user_id: int):
    return driver.select_one('select user_name from account where user_id="{}"'.format(user_id))


# 根据用户名密码获取用户，登录的时候需要
def get_user_by_username_and_password(driver: DatabaseDriver, username, password):
    return driver.select_one(sql='select * from account where user_name="{}" and user_password="{}"'.format(username, password))


if __name__ == "__main__":
    driver = connector.DatabaseDriver.DatabaseDriver()
    print(get_user_by_id)
    driver.close()
